package com.renchunlin.looerpager.view

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.viewpager.widget.ViewPager

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/6/18.
 * PS: Not easy to write code, please indicate.
 *
 * 拿到当前页，然后++，最后设置回去
 * /*var getCurrentItem = currentItem
        getCurrentItem++
        currentItem=getCurrentItem*/
 * 每隔一段时间就切换一次，就需要Handler
 * 处理触摸事件和轮询的冲突
 */
class SobViewPager : ViewPager {

    private val mHandler by lazy {
        Handler(Looper.myLooper()!!)
    }

    //这个是默认的切换时间
    companion object {
        const val DEFAULT_SWITCH_TIME = 3000L
    }

    private var looperTime = DEFAULT_SWITCH_TIME

    private lateinit var runnable: Runnable

    constructor(context: Context) : this(context, null)

    @SuppressLint("ClickableViewAccessibility")
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        //拿到当前页，然后++，最后设置回去
        //每隔一段时间就切换一次，就需要Handler
    }

    //处理触摸事件和轮询的冲突
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        when (ev?.action) {
            MotionEvent.ACTION_DOWN -> {
                stopLooper()
            }
            MotionEvent.ACTION_CANCEL -> {
                startLooper()
            }
            MotionEvent.ACTION_UP -> {
                startLooper()
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        startLooper()
    }

    private fun startLooper() {
        runnable = object : Runnable {
            override fun run() {
                mHandler.postDelayed(this, looperTime)
                //需要做轮询的方法
                var getCurrentItem = currentItem
                getCurrentItem++
                currentItem = getCurrentItem
            }
        }
        mHandler.postDelayed(runnable, looperTime)
    }

    private fun stopLooper() {
        mHandler.removeCallbacks(runnable)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopLooper()
    }

    fun setLooperTime(looperTime: Long) {
        this.looperTime = looperTime
    }
}